// 导入数据库连接对象
const db = require("../db");
// 导入配置信息
const { debug, info } = require("../config");

/**
 * 获取所有用户评论
 */
exports.getComments = async (req, res) => {
  const { page = 1, size = 4, nickname } = req.query;
  // 计算偏移量
  const offset = (page - 1) * size;
  let sql = `select com.com_user_id as u_id,com.com_article_id as a_id,com.id as c_id ,user.avatar,user.nickname,art.article_title,com.comment ,com.com_createdTime
  from blog_comment com,blog_user user,blog_article art 
  where com.com_user_id=user.id and com.com_article_id =art.id limit ${offset},${size}`;
  const sql1 = `select com.com_user_id as u_id,com.com_article_id as a_id,com.id as c_id ,user.avatar,user.nickname,art.article_title,com.comment ,com.com_createdTime
  from blog_comment com,blog_user user,blog_article art 
  where com.com_user_id=user.id and com.com_article_id =art.id and user.nickname like '%${nickname}%' limit ${offset},${size}`;
  if (nickname != "") {
    var [rows] = await db.promise().query(sql1);
    sql = `select count(*) as total from (${sql1}) middle_table`;
  } else {
    var [rows] = await db.promise().query(sql);
    sql = `select count(*) as total from blog_comment`;
  }
  // 计算总数
  const [result] = await db.promise().query(sql);
  if (rows.length != 0 && result.length != 0) {
    var { total } = result[0];
    // console.log(total);
    res.send(info(0, "获取所有评论成功", { total, rows }));
  } else {
    res.send(info(0, "暂无数据", []));
  }
};

/**
 * 删除用户评论
 */
exports.deleteComments = async (req, res) => {
  const { ids } = req.body;
  for (let i = 0; i < ids.length; i++) {
    let sql = `delete from blog_comment where id=${ids[i]}`;
    var [rows] = await db.promise().query(sql);
  }
  res.send(info(0, "删除指定用户评论成功", ""));
};
